package com.wjh.rules.core.engine;

import com.wjh.rules.common.EngineResponse;
import com.wjh.rules.core.rule.RuleUnit;

import java.util.*;

/**
 * @ClassName WholeLessRulesEngine
 * @Description: 执行所有的规则，返回所有满足的规则信息
 * @Author wjh
 * @Date 2020年6月22日
 */
public class WholeLessRulesEngine extends AbstractLessRulesEngine {

    /**
     * 执行规则引擎成功
     */
    @Override
    public EngineResponse fire(Map<String, Object> fact) {
        Iterator<RuleUnit> it = this.ll.iterator();
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            RuleUnit ru = it.next();
            //单个规则器匹配
            boolean result = ru.fire(fact,ru);
            if (result) {
                String groupId = ru.getGroupId();
                String id = ru.getId();
                List<String> ruleIdList = resultMap.get(groupId);
                if (ruleIdList == null) {
                    ruleIdList = new ArrayList<String>();
                }
                ruleIdList.add(id);
                resultMap.put(groupId, ruleIdList);
            }
        }
        return this.assebleFireResult(resultMap);
    }

    /**
     * 执行规则引擎失败
     */
    @Override
    public EngineResponse fireFail(Map<String, Object> fact) {
        Iterator<RuleUnit> it = this.ll.iterator();
        List<RuleUnit> ruleUnits = new ArrayList<>();
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            RuleUnit ru = it.next();
            //单个规则器匹配
            boolean result = ru.fire(fact, ru);
            if (!result) {
                String groupId = ru.getGroupId();
                String id = ru.getId();
                List<String> ruleIdList = resultMap.get(groupId);
                if (ruleIdList == null) {
                    ruleIdList = new ArrayList<String>();
                }
                ruleIdList.add(id);
                ruleUnits.add(ru);
                resultMap.put(groupId, ruleIdList);
            }
        }
        return this.assebleFireResult(resultMap, ruleUnits);
    }

}
